import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
 
sender = '631948983@qq.com'  # 发送方，填你的邮箱地址
receivers = ['2996410843@qq.com']  # 接收邮件的人，如果有多个则用逗号分隔
password = 'uobtitruozjmbcdi'   #邮箱密码：即我们从邮箱获取的授权码


#创建一个带附件的实例
message = MIMEMultipart()
mailserver = "smtp.qq.com"     #邮箱服务器地址
message['From'] = Header("编程胶囊", 'utf-8')
message['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
#邮件正文内容
message.attach(MIMEText('这是Python附件邮件发送测试……', 'plain', 'utf-8'))

# 构造附件1传送chpter7目录下的test.txt 文件
att1 = MIMEText(open('chapter7/test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写，写什么名字，邮件中就会显示什么名字
att1["Content-Disposition"] = 'attachment; filename="邀请函"'
message.attach(att1)

try:
    smtp = smtplib.SMTP(mailserver,port=25) # 连接邮箱服务器，smtp的端口号是25
    smtp.login(sender,password)  #登录邮箱
    smtp.sendmail(sender,receivers,message.as_string())# 参数分别是发送者，接收者，第三个是把上面的发送邮件的内容变成字符串
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")